#include "./src/shared.h"
#include "./src/types.h"

// Deferred shader textures
samplerRect dsEC;
samplerRect dsNorm;
samplerRect dsColor;

// Index into the light textures
uniform vec2 lightIndex[LIGHTS_PER_PASS];
samplerRect lightDir;
samplerRect lightPos;
samplerRect lightColor;
samplerRect prevImage;
uniform float lightScale;

void main (void)
{
	// TODO add ambient?, emmissive?, specular
	vec4 final;

	vec3 n = normalize(textureRect(dsNorm, gl_FragCoord));
	vec3 position = textureRect(dsEC, gl_FragCoord);
	vec4 diffuse = textureRect(dsColor, gl_FragCoord);

	// test has to be against a constant...
	for (int i=0; i<LIGHTS_PER_PASS; ++i) {
		vec3 lightPosition = textureRect(lightPos, lightIndex[i]);
		vec4 lightDiffuse = textureRect(lightColor, lightIndex[i]);
		vec3 l = normalize(lightPosition - position);

		float nDotL = max(dot(n,l),0.0);
		// TODO make adjustable
		float dis = max(0.5, length(lightPosition - position));
		// moved the /0.5 to *2.0 below..any faster?
		final += (lightDiffuse * nDotL)/((dis+1.5));	
		//final += (lightDiffuse * nDotL)/(0.5*(dis+1.5));	
		//final += (lightDiffuse * nDotL);	
	}
	final *= lightScale * diffuse * 2.0;
	//final *= lightScale * diffuse;

	gl_FragColor = textureRect(prevImage, gl_FragCoord) + final;
}

